<?php
namespace frontend\controllers;

use common\components\FrontBaseController;
use frontend\models\HryMember;
use frontend\models\HryOrder;
use Yii;
use \common\helps\tools;
use \common\helps\code;
use yii\db\Query;
use frontend\models\Hry;

/**
 * User controller
 */
class LoginController extends FrontBaseController
{

    public $modelClass = 'frontend\models\Member';
    public function init()
    {
        parent::init();
    }

    /*
     * 注册
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionRegister()
    {
        $member = new \frontend\models\Member();
        $redis = Yii::$app->cache;
        $request = $this->request;
        $params = $request->bodyParams;

        $code = $redis->get('userMobile' . $params['mobile']);
        if(empty($params['code'])){
            return code::error('codeEmpty');
        }
        if ($code === false) {
            return code::error('codeTime');
        }
        if ($code != $params['code']) {
            return code::error('codeFail');
        }
        $info = $member::findOneData('`id`',['mobile' => $params['mobile']]);
        if(!empty($info['id'])){
            return code::error('','该用户已存在');
        }
        $salt = tools::generateRandomString(8);
        $password = sha1(md5($params['password'].$salt));
        $username = substr($params['mobile'],-4,4)."用户";
        $username = tools::getMemberName($username);
        $res = $member::addData(['mobile' => $params['mobile'],'password' => $password,'salt' => $salt,'username' => $username,'province_id' => $params['province_code'],'city_id' => $params['city_code']]);
        if($res){
            //同步数据到好融艺
            $hry_model = new HryMember();
            $member_info = $member->find()->where(['mobile'=>$params['mobile']])->asArray()->one();
            if(!empty($member_info)){
                $member_info['password'] = md5($params['password']);
                $hry_member_id=$hry_model->insertHryMemberInfo($member_info);
                if($hry_member_id>0){
                 $member->saveData($member_info['id'],['hry_member_id' =>$hry_member_id]);
                }
            }
            return code::success($res);
        }else{
            return code::error('error');
        }
    }

    /*
     * 登录
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionLogin()
    {
        $member = new \frontend\models\Member();
        $session = Yii::$app->session;
        $redis = Yii::$app->cache;
        $request = $this->request;
        $params = $request->bodyParams;

        $code = $session->get('code');
        if(empty($params['code'])){
            return code::error('codeEmpty');
        }
        if(!empty($code['expire_time']) && $code['expire_time'] < time()){
            return code::error('codeTime');
        }
        if($code['title'] != $params['code']){
            return code::error('codeFail');
        }
        $info = $member::findOneData('`*`',['mobile' => $params['mobile']]);
        if(empty($info['id'])){
            return code::error('','用户不存在');
        }
        if($info['password'] == sha1(md5($params['password'].$info['salt'])) || (md5(trim($params['password'])) == $info['password'] || $info['password'] == md5(md5(trim($params['password']))) || password_verify($params['password'],$info['password']))){  // 加入了好融艺密码验证
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $token = md5(tools::generateRandomString(32));
                if (!empty($info['token']))
                    $redis->hdel('member_info', $info['token']);
                $info['login_time'] = time();
                $info['login_ip'] = tools::getIp();
                $info['token'] = $token;
                $redis->hset('member_info', $token, json_encode($info));
                $redis->set('member' . $info['id'], $token, 2592000);
//                $session->set('member_id',$info['id']); // 取消使用 by hey_heyang

                $member->saveData($info['id'],['token' => $token]);
                $transaction->commit();
                return code::success(['token' => $token],'登录成功');
            } catch (\Exception $e) {
                $transaction->rollBack();
                throw $e;
            }
        }else{
            return code::error('','密码错误，请重新输入');
        }
    }

    /*
     * 获取图形验证码
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionGetPicCode()
    {
        $imageCode = tools::verifyCode();
        return code::success($imageCode);
    }

    /*
     * 获取session_id
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionGetSessionId()
    {
        if (!session_id()) session_start();
        $res = session_id();
        return code::success($res);
    }

    /*
     * 判断token是否有效
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionCheckToken()
    {
        $redis = Yii::$app->cache;
//        $session = Yii::$app->session;
        $headers = Yii::$app->request->headers;
        $token =$headers->get('token');
        if(empty($token)){
            return code::error('emptyToken');
        }
        $info = json_decode($redis->hget('member_info', $token),true);
//        $admin_id = $session->get('member_id');
//        if(empty($admin_id)){
//            return code::success(false);
//        }  //取消使用
        if(empty($info)){
            return code::success(false);
        }
        $expire = $redis->get('member' . $info['id']);
        if(empty($expire)){
            return code::success(false);
        }
        return code::success(true);
    }

    /*
     * 获取手机验证码
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionGetPhoneCode()
    {
        $redis = Yii::$app->cache;
        $session = Yii::$app->session;
        $member = new \frontend\models\Member();
        $request = $this->request;
        $params = $request->bodyParams;
        $code = $session->get('code');
        if(empty($params['code'])){
            return code::error('codeEmpty');
        }
        if(!empty($code['expire_time']) && $code['expire_time'] < time()){
            return code::error('codeTime');
        }
        if($code['title'] != $params['code']){
            return code::error('codeFail');
        }
        $info = $member::findOneData('`id`',['mobile' => $params['mobile']]);
        if(!empty($info['id'])){
            return code::error('','该用户已存在，请登录');
        }
        return code::success(true);
//        $pcode = tools::createRandomNum(4);
//        $redis->set('user_mobile:' . $params['mobile'], $pcode, 300);
//        $res = tools::SmsToSend($params['mobile'],$pcode);
//        if($res['code'] === 0){
//            return code::success($res['msg']);
//        }else{
//            return code::error('',$res['msg']);
//        }
    }

    /*
     * 获取手机验证码
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionGetMobileCode()
    {
        $redis = Yii::$app->cache;
        $member = new \frontend\models\Member();
        $request = $this->request;
        $params = $request->bodyParams;

        if(empty($params['mobile'])){
            return code::error('mistake');
        }
        $info = $member::findOneData('`id`',['mobile' => $params['mobile']]);
        if(!empty($info['id'])){
            return code::error('','该用户已存在，请登录');
        }
        $row = $redis->get('getCode'.$params['mobile']);
        $num = 1;
        if($row !== false){
            if($row == 5){
                return code::error('','验证码发送已到达上限');
            }
            $num = $row + 1;
        }
        $redis->set('getCode'.$params['mobile'],$num,3600);
        $pcode = tools::createRandomNum(4);
        $redis->set('userMobile' . $params['mobile'], $pcode, 300);
        $res = tools::SmsToSend($params['mobile'],$pcode);
        if($res['code'] === 0){
            return code::success($res['msg']);
        }else{
            return code::error('',$res['msg']);
        }
    }

    public function actionLogOut(){
        $headers = Yii::$app->request->headers;
        $token =$headers->get('token');
        $redis = Yii::$app->cache;
        if(empty($token)) return code::error('error','参数错误');
        $info =  json_decode($redis->hget('member_info', $token),true);
        $redis->hdel('member_info',$token);
        if(!empty($info['id'])){
            $redis->del('member'.$info['id']);
        }
        return code::success();
    }



}
